/*
 * Created on Nov 25, 2003
 */
package com.unash.util;

/**
 * @author Ashwini Gokhale
 */

import java.io.IOException;
import java.io.InputStream;

/**
 * This function reads up to len bytes of data from the input stream
 * into an array of bytes. This function does not return until len bytes
 * have been read, an EOF is received from the peer, or an error occurs.
 * @param bs Ber Encoded Stream
 * @param len Length of bytes to be read
 * @param buf buffer to store the read bytes
 * @return No of bytes read. < 0 if len bytes are not read. 
 */
public class NetworkIO{
	public static int readNBytes(InputStream bs, int len, byte[] buf) 
		throws IOException
	{
		int cnt;
		int rc;
		int offset = 0;
		
		cnt = len;
		while(cnt > 0){
			rc = bs.read(buf,offset,cnt);
			if(0 > rc){
				return -1;			
			}//if(0 > rc)
			
			if(rc == 0)
				return cnt-len;
			
			offset += rc;
			cnt -= rc;
		}//while(cnt > 0)
		
		return len;
	}//readNBytes
	
}//NetworkIO